import java.util.Iterator;

public class LinkStack {
    public static void main(String[] args) {
        LinkedListStack<Integer> stack = new LinkedListStack<Integer>(3);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        System.out.println(stack.peek());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}
class LinkedListStack<E> implements Stack<E>,Iterable<E>{

    int size;
    int capcity;



    class Node<E>{
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    Node<E>  head = new Node<E>(null,null);

    public  LinkedListStack(int capcity) {
        this.capcity = capcity;
    }

    @Override
    public boolean push(E value) {
        if (isFull()){
            return false;
        }
        Node<E> add = new Node<E>(value,head.next);
        head.next = add;
        size++;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()){
            return null;
        }
        Node<E> remove = head.next;
        head.next = remove.next;
        size--;
        return remove.value;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public boolean isFull() {
        return size==capcity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p!=null;
            }

            @Override
            public E next() {
                E val = p.value;
                p = p.next;
                return val;
            }
        };
    }
}
